# Differentiable Augmentation for Data-Efficient GAN Training
# Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han
# https://arxiv.org/pdf/2006.10738

import mindspore
from mindspore.common.tensor import Tensor
import mindspore.ops as ops
import mindspore.ops.operations as P
import random
import mindspore.numpy as np

def DiffAugment(x, policy='', channels_first=True):
    if policy:
        if not channels_first:
            x = P.Transpose()(x, (0, 3, 1, 2))
        for p in policy.split(','):
            for f in AUGMENT_FNS[p]:
                x = f(x)
        if not channels_first:
            x = P.Transpose()(x, (0, 2, 3, 1))
    return x


def rand_brightness(x):
    x = x + (P.UniformReal(seed=2)((P.Shape()(x)[0], 1, 1, 1)) - 0.5)
    return x


def rand_saturation(x):
    x_mean = P.ReduceMean(keep_dims=True)(x, axis=1)
    x = (x - x_mean) * (P.UniformReal(seed=2)((P.Shape()(x)[0], 1, 1, 1)) * 2) + x_mean
    return x


def rand_contrast(x):
    x_mean = P.ReduceMean(keep_dims=True)(x, axis=[1, 2, 3])
    x = (x - x_mean) * (P.UniformReal(seed=2)((P.Shape()(x)[0], 1, 1, 1)) + 0.5) + x_mean
    return x


def rand_translation(x, ratio=0.2):
    shift_x, shift_y = int(P.Shape()(x)[2] * ratio + 0.5), int(P.Shape()(x)[3] * ratio + 0.5)
    
    translation_x = P.UniformInt(seed=10)((P.Shape()(x)[0], 1, 1), Tensor(-shift_x, mindspore.dtype.int32), Tensor(shift_x + 1, mindspore.dtype.int32))
    translation_y = P.UniformInt(seed=10)((P.Shape()(x)[0], 1, 1), Tensor(-shift_y, mindspore.dtype.int32), Tensor(shift_y + 1, mindspore.dtype.int32))
    
    # arange_1 = np.arange(P.Shape()(x)[0], dtype=mindspore.dtype.int64)
    # arange_2 = np.arange(P.Shape()(x)[2], dtype=mindspore.dtype.int64)
    # arange_3 = np.arange(P.Shape()(x)[3], dtype=mindspore.dtype.int64)
    
    # print("size 1: {}, size 2: {}, size 3: {}".format(str(P.Shape()(arange_1)), str(P.Shape()(arange_2)), str(P.Shape()(arange_3))))
    
    grid_batch, grid_x, grid_y = P.Meshgrid(indexing="ij")((
        np.arange(P.Shape()(x)[0], dtype=mindspore.dtype.int64),
        np.arange(P.Shape()(x)[2], dtype=mindspore.dtype.int64),
        np.arange(P.Shape()(x)[3], dtype=mindspore.dtype.int64))
    )
    
    # print("size grid_batch: {}, size grid_x: {}, size grid_y: {}".format(str(P.Shape()(grid_batch)), str(P.Shape()(grid_x)), str(P.Shape()(grid_y))))
    # print("size translation_x: {}, size translation_y: {}".format(str(P.Shape()(translation_x)), str(P.Shape()(translation_y))))

    grid_x = ops.clip_by_value(grid_x + translation_x + 1, 0, P.Shape()(x)[2] + 1)
    grid_y = ops.clip_by_value(grid_y + translation_y + 1, 0, P.Shape()(x)[3] + 1)
    x_pad = ops.Pad(((0, 0), (0, 0), (1, 1), (1, 1)))(x)
    x = P.Transpose()(x_pad, (0, 2, 3, 1))
    x = P.Transpose()(x[grid_batch, grid_x, grid_y], (0, 3, 1, 2))
    
    return x


def rand_cutout(x, ratio=0.5):
    if random.random() < 1.0:
        cutout_size = int(P.Shape()(x)[2] * ratio + 0.5), int(P.Shape()(x)[3] * ratio + 0.5)
        offset_x = P.UniformInt(seed=10)((P.Shape()(x)[0], 1, 1), Tensor(0, mindspore.dtype.int32), Tensor(P.Shape()(x)[2] + 1 - cutout_size[0] % 2, mindspore.dtype.int32))
        offset_y = P.UniformInt(seed=10)((P.Shape()(x)[0], 1, 1), Tensor(0, mindspore.dtype.int32), Tensor(P.Shape()(x)[3] + 1 - cutout_size[1] % 2, mindspore.dtype.int32))
        
        grid_batch, grid_x, grid_y = P.Meshgrid(indexing="ij")((
            np.arange(P.Shape()(x)[0], dtype=mindspore.dtype.int64),
            np.arange(cutout_size[0], dtype=mindspore.dtype.int64),
            np.arange(cutout_size[1], dtype=mindspore.dtype.int64))
        )
        
        # print("size grid_batch: {}, size grid_x: {}, size grid_y: {}".format(str(P.Shape()(grid_batch)), str(P.Shape()(grid_x)), str(P.Shape()(grid_y))))
        # print("size cutout_size: {}, offset_x: {}, size offset_y: {}".format(str(cutout_size), str(P.Shape()(offset_x)), str(P.Shape()(offset_y))))


        grid_x = ops.clip_by_value(grid_x + offset_x - cutout_size[0] // 2, 0, P.Shape()(x)[2] - 1)
        grid_y = ops.clip_by_value(grid_y + offset_y - cutout_size[1] // 2, 0, P.Shape()(x)[3] - 1)
        mask = ops.Ones()((P.Shape()(x)[0], P.Shape()(x)[2], P.Shape()(x)[3]), x.dtype)
        mask[grid_batch, grid_x, grid_y] = 0.0 #
        # print("shape of mask is ", P.Shape()(mask))
        x = x * ops.ExpandDims()(mask, 1)
    return x

def rand_rotate(x, ratio=0.5):
    k = random.randint(1,3)
    if random.random() < ratio:
        x = np.rot90(x, k=k, axes=[2,3])
    return x

AUGMENT_FNS = {
    'color': [rand_brightness, rand_saturation, rand_contrast],
    'translation': [rand_translation],
    'cutout': [rand_cutout],
    'rotate': [rand_rotate],
}
